package org.example.edusmart.controller.Admin;

import org.example.edusmart.pojo.UserPojo;
import org.example.edusmart.request.admin.ChangeUserRolePojo;
import org.example.edusmart.request.admin.RoleListPojo;
import org.example.edusmart.service.UserService;
import org.example.edusmart.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class ChangeUserRoleController {

    @Autowired
    private UserService userService;

    /**
     * 根据学工号查找不属于该用户的角色信息，用于修改当前用户的角色信息
     *
     * @param roleListPojo 学工号
     * @return 不属于该用户的角色信息
     */
    @PostMapping("/roleList/")
    @PreAuthorize("hasAuthority('admin_permission')")
    public Result roleList(@RequestBody RoleListPojo roleListPojo) {
        List<HashMap<String, Object>> RoleList = userService.getRoleList(roleListPojo);

        return new Result(RoleList, 200, "查询成功");
    }

    /**
     * 修改用户角色权限
     * @param changeUserRolePojo 用户名 修改的角色Id（从上一个接口取）
     * @return
     */
    @PostMapping("changeUserRole")
    @PreAuthorize("hasAuthority('admin_permission')")
    @Transactional(rollbackFor = Exception.class)
    public Result changeUserRole(@RequestBody ChangeUserRolePojo changeUserRolePojo) {

        // 根据用户名来查找用户Id
        UserPojo a = userService.checkUserByUsername(changeUserRolePojo.getUsername());
        String userId = String.valueOf(a.getUserId());

        // 入参
        HashMap<String, Object> inParameter = new HashMap<>() {{
            put("userid", userId);
            put("roleId", changeUserRolePojo.getRoleId());
        }};

        // 执行更新语句，用户Id作为条件，修改

        Integer judge = userService.changeUserRoleByUserid(inParameter);


        if (judge == 1) {
            return new Result(200, "修改成功");
        }
        return new Result(200, "修改失败");

    }


}
